package internationalenergytradingplatform.utils;

import com.zhenzi.sms.ZhenziSmsClient;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Data
@AllArgsConstructor
@Slf4j
@Component
public class MessageUtils {


    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     *
     * @author yingfeng
     * @date 2024/2/27 12:45
    将验证码存放在redis中
     */
    public String generateVerificationCode(String phoneNumber ){
        // 生成随机验证码
        String code = generateRandomCode();

        // 存储验证码到Redis，设置过期时间为5分钟
        redisTemplate.opsForValue().set(phoneNumber, code, 5, TimeUnit.MINUTES);

        return code;
    }

    /**
     *
     * @author yingfeng
     * @date 2024/2/27 21:41
     生成验证码
     */
    private String generateRandomCode() {
        // 生成6位随机数字验证码
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }
    /**
     *
     * @author yingfeng
     * @date 2024/2/27 12:45
    发送验证码
     */
    public String sendSMS(String number, String templateId) throws Exception {
        String appId = "112752";
        String appSecret = "2440c241-3023-416c-b8d3-606fe4b2a500";
        String apiUrl = "https://sms_developer.zhenzikj.com";
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", number);
        params.put("templateId", templateId);
        String[] templateParams = new String[2];
        templateParams[0] = generateVerificationCode(number);
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        String result = client.send(params);
        return result;
    }

    /**
     *
     * @author yingfeng
     * @date 2024/2/27 12:45
    校验验证码
     */
    public boolean validateSMS(String tele, String code){
        // 从Redis中获取存储的验证码
        String storedCode = redisTemplate.opsForValue().get(tele);

        // 判断验证码是否匹配
        return code.equals(storedCode);
    }




}
